package org.greenwire.islandharvester;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.greenwire.islandharvester.helper.HarvestHelper;
import org.greenwire.islandharvester.helper.LoginHelper;

import com.gargoylesoftware.htmlunit.WebClient;

public class HappyIslandAutoHarvester {	
	
	private final Log logger = LogFactory.getLog(HappyIslandAutoHarvester.class);
	
	private String userName;
	private String passwd;
	
	public HappyIslandAutoHarvester(String userName, String passwd){
		this.userName = userName;
		this.passwd = passwd;
	}
	
	public void begin() {
		Timer timer = new Timer(false);
		timer.schedule(new MyTimerTask(), 0, 2 * 60 * 1000); // 立即启动一个执行间隔120秒的定时任务
	}
	
	class MyTimerTask extends TimerTask {
		@Override
		public void run() {
			WebClient webClient = new WebClient();webClient.setJavaScriptEnabled(false);
			LoginHelper loginHelper = new LoginHelper(webClient);
			
			if(!loginHelper.doLogin(userName, passwd)){
				logger.error("Login failed, terminate program!");
				return;
			}
			
			HarvestHelper harvestHelper = new HarvestHelper(webClient);
			harvestHelper.startHarvest();				
		}
	}
}
